package com.noble.glamour.module.local.chat;

import com.noble.glamour.bean.my.GiftsList;
import com.noble.glamour.module.local.chat.utils.MsgUtils;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.socket.IMProxy;
import com.noble.glamour.module.logic.socket.NetData;
import com.noble.glamour.module.logic.socket.listener.IMListener;
import com.noble.library.log.PLogger;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.meether.chat.MessageConstant;
import com.noble.meether.chat.msgtype.CommonMessage;
import com.noble.meether.chat.msgtype.base.BaseMessage;
import com.noble.meether.chat.ui.agora.RtcUIShow;
import com.noble.meether.chat.ui.agora.dialog.listener.GiftSendListener;
import com.noble.meether.chat.ui.agora.manager.RtcMessageMgr;
import com.noble.meether.chat.ui.agora.model.AgoraConstant;
import com.noble.meether.chat.ui.agora.util.RtcJointChannel;
import com.noble.meether.chat.ui.agora.util.RtcUtil;
import com.noble.meether.chat.ui.imui.listener.ReceiveMsgListener;
import com.noble.meether.chat.ui.imui.util.IMChatUtil;
import com.noble.meether.chat.unread.UnreadMgr;

import org.json.JSONObject;

/**
 * 接收消息处理类
 */
public class RecMessageMgr implements IMListener {

    public void init() {
        IMProxy.getInstance().attach(this);
    }

    public void release() {
        IMProxy.getInstance().detach(this);
    }

    @Override
    public void onMessage(NetData data) {
        try {
            PLogger.d("reMsg-jsonStr=" + data.getMsgBody());
            JSONObject object = new JSONObject(data.getMsgBody());
            if (data.getFromId() <= 0) {//如果小于或等于0
                data.setFromId(object.optLong("UidFrom"));
            }
            detachMsg(data);
        } catch (Exception e) {
            PLogger.printThrowable(e);
        }
    }

    /**
     * @param data 消息分发
     */
    private void detachMsg(NetData data) {
        int type = data.getMsgType();
        handleDB(data);
        handleCommonMsg(type, data);
        switch (type) {
            case MessageConstant.MSG_SYS_NOTICE:         // 新系统公告, 更新本地公告列表
                ModuleMgr.getCommonMgr().getNoticeMsg();
                break;

            case MessageConstant.MSG_ADD_BLACK:         // 加入黑名单
            case MessageConstant.MSG_DELE_FRIEND:       // 删除好友
                handleFriendStatus(data.getFromId(), type);
                break;
            case MessageConstant.MSG_ID_TEXT:       // 文字消息
                if (ModuleMgr.getRtcEnginMgr().getEngineConfig().mJoinStatus &&  // 音视频聊天中
                        ModuleMgr.getRtcEnginMgr().getEngineConfig().mOtherId == data.getFromId()) {
                    CommonMessage message = new CommonMessage();
                    message.parseJson(data.getMsgBody());
                    MsgMgr.getInstance().sendMsg(MsgType.MT_Msg_AvChat_Other, message.getText());
                }
                break;
            case MessageConstant.MSG_ID_GIFT:       // 礼物消息
                handleGift(data);
                break;
            case MessageConstant.MSG_ASK_FRIEND:  // 申请好友消息
                MsgUtils.handleAskFriend(1, false);
                break;

            // 1对1音视频消息
            case MessageConstant.MSG_ID_CHAT_AUDIO:  // 语音通话请求
                RtcMessageMgr.getInstance().singleAV(data.getFromId(), AgoraConstant.RTC_CHAT_VOICE);
                break;
            case MessageConstant.MSG_ID_CHAT_VIDEO:  // 视频通话请求
                RtcMessageMgr.getInstance().singleAV(data.getFromId(), AgoraConstant.RTC_CHAT_VIDEO);
                break;
            case MessageConstant.MSG_ID_STOP_AUDIO:  // 语音挂断
            case MessageConstant.MSG_ID_STOP_VIDEO:   // 视频挂断
                RtcJointChannel.getInstance().userOffline();
                break;

            case MessageConstant.MSG_ID_ACCEPT_AUDIO: // 接受语音邀请消息
            case MessageConstant.MSG_ID_ACCEPT_VIDEO: // 接受视频邀请消息
                RtcMessageMgr.getInstance().acceptAV(data.getContent());
                break;
            case MessageConstant.MSG_ID_REJECT_AUDIO:
            case MessageConstant.MSG_ID_REJECT_VIDEO:
                RtcMessageMgr.getInstance().rejectAv(data.getFromId());
                break;
            case MessageConstant.MSG_USER_BUSY:   // 用户忙
                MsgUtils.showToast("用户忙");
                break;
            case MessageConstant.MSG_USER_FREE:  // 用户空闲
                RtcUIShow.showRtcInitAct(App.getActivity());
                break;

            // 抢聊消息
            case MessageConstant.MSG_ROB_NOTICE:   // 男性收： 女性抢聊消息
                RtcMessageMgr.getInstance().robGrilMsg(data);
                break;
            case MessageConstant.MSG_ROB_CANCEL:   // 女性收：  男性已经关闭群发
                RtcMessageMgr.getInstance().hasCancelRob(data);
                break;
        }
    }

    /**
     * 普通消息：文字/图片/小视频
     */
    private Runnable msgRunable;

    private void handleCommonMsg(int type, final NetData data) {
        final ReceiveMsgListener listener = IMChatUtil.getInstance().getReceiveMsgListener();
        if (listener == null || UnreadMgr.whisperId != data.getFromId() || !MsgUtils.isSaveMsg(type))
            return;

        msgRunable = () -> listener.onReceiveMsg(data);
        MsgMgr.getInstance().runOnUiThread(msgRunable);
    }

    /**
     * 私聊页面好友状态处理
     */
    private void handleFriendStatus(long fromID, final int msgType) {
        final ReceiveMsgListener listener = IMChatUtil.getInstance().getReceiveMsgListener();
        if (listener == null || UnreadMgr.whisperId != fromID) return;
        msgRunable = () -> listener.onReceiveFriendStatusMsg(msgType);
        MsgMgr.getInstance().runOnUiThread(msgRunable);
    }

    /**
     * 礼物消息
     */
    private GiftsList.GiftInfo info = new GiftsList.GiftInfo();
    private Runnable giftRunnable;

    private void handleGift(NetData data) {
        final GiftSendListener listener = RtcUtil.getInstance().getGiftSendListener();
        if (listener == null) return;

        CommonMessage commonMessage = new CommonMessage();
        commonMessage.parseGift(data.getContent());
        info.setName(commonMessage.getGiftName());
        info.setPic(commonMessage.getGiftIcon());
        info.setNum(commonMessage.getGiftNum());
        giftRunnable = () -> listener.sendGiftSuccess(info);
        MsgMgr.getInstance().runOnUiThread(giftRunnable);
    }

    /**
     * @param data 插入数据库
     */
    private void handleDB(NetData data) {
        if (!MsgUtils.isSaveMsg(data.getMsgType())) {
            return;
        }

        // 消息存储
        BaseMessage baseMessage = new BaseMessage();
        baseMessage.setUidFrom(data.getFromId());
        baseMessage.setUidTo(data.getTuid());
        baseMessage.setMsgType(data.getMsgType());
        baseMessage.setContent(data.getContent());

        baseMessage.setIsSender(0);
        baseMessage.setWhisperId(data.getFromId());
        ModuleMgr.getDbMgr().getMsgCache().insertMsg(baseMessage, null);

        // 不是正在聊天对象
        if (UnreadMgr.whisperId != data.getFromId()) {
            ModuleMgr.getNotifyMgr().startNotify(baseMessage);   // 通知消息

            MsgUtils.handleSbUnread(data.getFromId());  // 未读处理
        }

        // 更新信箱消息列表
        IMChatUtil.getInstance().updateMsgList(baseMessage);
    }
}